package com.dwxt.cdms.service;

import com.dwxt.cdms.admin.service.HistoryServiceAdmin;
import com.dwxt.cdms.api.common.utils.DateUtil;
import com.dwxt.cdms.api.common.utils.StringUtil;
import com.dwxt.cdms.base.OperateCategory;
import com.dwxt.cdms.constant.WarningType;
import com.dwxt.cdms.dao.AdminUserMapper;
import com.dwxt.cdms.dao.WarningMapper;
import com.dwxt.cdms.entity.AdminUser;
import com.dwxt.cdms.entity.Customer;
import com.dwxt.cdms.entity.EquipmentCustom;
import com.dwxt.cdms.entity.Warning;
import com.dwxt.cdms.entity.yumeng.LocData;
import com.dwxt.cdms.entity.yumeng.LogData;
import com.dwxt.cdms.exception.CustomException;
import com.dwxt.cdms.service.wx.WxMessageService;
import com.dwxt.cdms.util.GpsUtils;
import com.dwxt.cdms.view.SOSPoint;
import com.dwxt.cdms.view.WarningView;
import com.dwxt.cdms.vo.SelectWaringVo;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.constant.VariableConstants;
import com.dwxt.common.util.IDUtils;
import com.dwxt.common.util.PartyUtil;
import com.dwxt.common.util.SnowIdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 报警 Service
 *
 * @author Kuang.JiaZhuo
 * @date 2020-09-24 15:51
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class WarningService {

    private final WarningMapper warningMapper;
    private final CustomerService customerService;
    private final EquipmentCustomService equipmentCustomService;
    private final HistoryServiceAdmin historyServiceAdmin;
    private final StationService stationService;
    private final AdminUserMapper adminUserMapper;
    private final WxMessageService wxMessageService;

    /**
     * @方法名：insertWarningBySos
     * @描述： 新增sos报警信息
     * @作者： kjz
     * @日期： Created in 2020/9/24 15:57
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertWarningBySos(LogData logData) {

        Customer customer = customerService.selectCustomerById(logData.getCustomerId());
        String content = "【" + customer.getName() + "】SOS呼叫告警，请您注意！";

        Warning warning = new Warning();
        warning.setId(SnowIdUtil.getInstance().nextId());
        warning.setCreateTime(LocalDateTime.now());
        warning.setType(VariableConstants.STRING_CONSTANT_2);
        warning.setLogId(logData.getId());
        warning.setState(VariableConstants.STRING_CONSTANT_0);
        warning.setWarningTime(logData.getTime());
        warning.setCustomerId(logData.getCustomerId());
        warning.setContent(content);
        warning.setIsDelete(VariableConstants.STRING_CONSTANT_0);

        SOSPoint sosPoint = logData.getSosPoint();
        if (sosPoint != null) {
            warning.setLatitude(sosPoint.getLatitude());
            warning.setLongitude(sosPoint.getLongitude());
        }
        return warningMapper.insert(warning);
    }

    /**
     * @方法名：insertWarningElectronic
     * @描述： 新增电子围栏报警
     * @作者： liu.hongfei
     * @日期： Created in 2020/9/25 14:15
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertWarningElectronic(LocData locData) {
        //加入客户id
        String deviceIdentity = locData.getDeviceIdentity();
        EquipmentCustom equipmentCustom = equipmentCustomService.selectEquipmentCustomByDeviceIdentity(deviceIdentity);
        Customer customer = customerService.selectCustomerById(equipmentCustom.getCustomerId());
        String content = "用户：【" + customer.getName() + "】走出活动范围，请您注意！";
        Warning warning = new Warning();
        warning.setId(SnowIdUtil.getInstance().nextId());
        warning.setCreateTime(LocalDateTime.now());
        warning.setType(VariableConstants.STRING_CONSTANT_1);
        warning.setState(VariableConstants.STRING_CONSTANT_0);
        warning.setWarningTime(locData.getTime());
        warning.setCustomerId(customer.getId());
        warning.setContent(content);
        warning.setIsDelete(VariableConstants.STRING_CONSTANT_0);
        warning.setLongitude(locData.getLongitude());
        warning.setLatitude(locData.getLatitude());
        return warningMapper.insert(warning);
    }

    /**
     * @方法名：selectWarningByPage
     * @描述： 按条件查询预警列表(带分页)
     * @作者： kjz
     * @日期： Created in 2020/9/24 17:27
     */
    public PageInfo<WarningView> selectWarningByPage(SelectWaringVo selectWaringVo) {
        Integer stationId;
        Integer loginUserStation = stationService.getLoginUserStation();
        if (selectWaringVo.getStationId() == null) {
            stationId = loginUserStation;
        } else {
            stationId = selectWaringVo.getStationId();
        }
        selectWaringVo.setStationId(stationId);
        PageHelper.startPage(selectWaringVo.getPageNum(), selectWaringVo.getPageSize());
        List<WarningView> list = warningMapper.selectWarningByCondition(selectWaringVo);
        list.forEach(warningView -> {
            //经纬度： WG1984 -> GCJ02
//            System.err.println(JSON.toJSON(warningView));
            String longitude = warningView.getLongitude();
            String latitude = warningView.getLatitude();
            if (StringUtil.isNotBlank(longitude) && StringUtil.isNotBlank(latitude)) {
                double[] nautica = GpsUtils.wgs84togcj02(Double.parseDouble(longitude), Double.parseDouble(latitude));
                warningView.setLongitude(String.valueOf(nautica[0])).setLatitude(String.valueOf(nautica[1]));
            }

        });
        PageInfo<WarningView> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * @方法名：updateStateById
     * @描述： 更新预警的处理状态
     * @作者： kjz
     * @日期： Created in 2020/9/28 10:33
     */
  /*  public int updateStateById(String id,String conduct) {
        Warning warning = warningMapper.selectWarningById(id);
        String state = warning.getState();

        if(VariableConstants.STRING_CONSTANT_0.equals(state)){
            //更改为已处理，处理方式就必须传
            Optional.ofNullable(conduct).orElseThrow(() -> new CustomException(StatusCode.CONDUCT_IS_NOT_NULL));

            warning.setState(VariableConstants.STRING_CONSTANT_1).setConduct(conduct);
        }else if(VariableConstants.STRING_CONSTANT_1.equals(state)){
            warning.setState(VariableConstants.STRING_CONSTANT_0).setConduct(null);
        }
        return warningMapper.updateByPrimaryKeySelective(warning);
    }*/


    /**
     * @方法名：updateStateById
     * @描述： 更改为已处理
     * @作者： kjz
     * @日期： Created in 2020/10/22 14:43
     */
    public int updateStateById(String id, String conduct) {
        Warning warning = warningMapper.selectWarningById(id);
        if (warning.getState().equals("1")) {
            return 0;
        }
        warning.setConduct(conduct);
        String state = warning.getState();
        if (VariableConstants.STRING_CONSTANT_0.equals(state) || state == null) {
            //更改为已处理，处理方式就必须传
            Optional.ofNullable(conduct).orElseThrow(() -> new CustomException(StatusCode.CONDUCT_IS_NOT_NULL));
            //插入操作记录
            historyServiceAdmin.generate("将报警改为已处理:" + warning.getId(), OperateCategory.UPDATE);
            warning.setState(VariableConstants.STRING_CONSTANT_1);
        }
        int i = this.warningMapper.updateByPrimaryKeySelective(warning);
        Customer customer = customerService.selectCustomerById(warning.getCustomerId());
        String content = warning.getContent();
        String detail = content.substring(content.indexOf("】") + 1, content.indexOf("，")==-1? content.indexOf(","):-1);
        String currentUserId = PartyUtil.getCurrentUserId();
        AdminUser adminUser = adminUserMapper.selectByPrimaryKey(Integer.valueOf(currentUserId));
        String handleType = "";//【石万猛】摘除报警,请您注意！
        //小程序消息通知本人
        if (conduct.equals("1")) {
            handleType = "电话处理";
        } else if (conduct.equals("2")) {
            handleType = "上门处理";
        }else if (conduct.equals("3")) {
            handleType = "第三方处理";
        }else if (conduct.equals("4")) {
            handleType = "短信推送";
        }else if (conduct.equals("5")) {
            handleType = "小程序消息推送";
        }else if (conduct.equals("6")) {
            handleType = "预警处理流程";
        }
        try {
            Date createTime = Date.from(warning.getCreateTime().atZone(ZoneId.systemDefault()).toInstant());
            //小程序
            wxMessageService.sendHandleMessageToMinApp(handleType, customer, detail, createTime);
            // 公众号
            if (!conduct.equals("5")) {
                wxMessageService.sendHandleMessageToGzh(customer, detail, new Date(), adminUser.getUsername(), handleType);
            }
        } catch (Exception e) {
            log.error("消息推送失败");
        }
        return i;
    }

    public void insertWarning(Integer customerId,String type,String imei,String deviceCategory) {
        Customer customer = customerService.selectCustomerById(customerId);
        String content = "";
        if (WarningType.ELECTRONIC.equals(type)) {
            content = "【" + customer.getName() + "】电子围栏报警，请您注意！";
        } else if (WarningType.SOS.equals(type)) {
            content = "【" + customer.getName() + "】SOS报警，请您注意！";
        }else if (WarningType.SOS_CANCEL.equals(type)) {
            content = "【" + customer.getName() + "】SOS报警取消，请您注意！";
        }else if (WarningType.POWER.equals(type)) {
            content = "【" + customer.getName() + "】低电量报警，请您注意！";
        }else if (WarningType.REMOVE.equals(type)) {
            content = "【" + customer.getName() + "】摘除报警,请您注意！";
        }else if (WarningType.FALL.equals(type)) {
            content = "【" + customer.getName() + "】跌倒报警,请您注意！";
        }else if (WarningType.SHUTDOWN.equals(type)) {
            content = "【" + customer.getName() + "】关机报警，请您注意！";
        }
        Warning warning = new Warning();
        warning.setId(IDUtils.genItemId());
        warning.setContent(content);
        warning.setCategory(deviceCategory);
        warning.setImei(imei);
        warning.setCustomerId(customerId);
        warning.setType(type);
        warning.setState(VariableConstants.STRING_CONSTANT_0);
        warning.setWarningTime(DateUtil.parseStr(new Date(), DateUtil.FMT_YYYYMMDD_HHMMSS));
        warning.setIsDelete(VariableConstants.STRING_CONSTANT_0);
        warning.setCreateTime(LocalDateTime.now());
        warningMapper.insertSelective(warning);
    }
}
